// * @author xuziqiang
// * @date 2020/6/4

import 'dart:async';
import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

//这里视情况而定  代码 拷贝自 flutter-go

//const create_wechat_nickname_table =
//    "CREATE TABLE  IF NOT EXISTS  wechat_nickname ("
//    "nickNameId	INTEGER PRIMARY KEY autoincrement ,"
//    "nickName TEXT NOT NULL  "
//    ")";

const create_train_record = "CREATE TABLE  IF NOT EXISTS  train_record ("
    "id	INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,"
    "rows	Integer ,"
    "columns	Integer ,"
    "responseTime Integer,"
    "handTime Integer,"
    'wholeTime Integer,'
    "mode Integer," //  1简易   2专业  4随机  可以类比一下Linux里面的权限管理 1 2 3 4 5 6 7都有它的意义
    "date DATETIME"
    ")";

const createSql = {
  'create_train_record': create_train_record,
};

class Provider_db {
  static Database db;

  // ignore: non_constant_identifier_names
  String TAG = "Provider_DB ~~~~~";

  // 获取数据库中所有的表
  Future<List> getTables() async {
    if (db == null) {
      return Future.value([]);
    }
    List tables = await db
        .rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
    List<String> targetList = [];
    tables.forEach((item) {
      targetList.add(item['name']);
    });
    return targetList;
  }

  //初始化数据库

  Future init(bool isCreate) async {
    //Get a location using getDatabasesPath
    String databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'flutter.db');
    LogUtil.v(TAG + path);
    if (await Directory(dirname(path)).exists()) {
      LogUtil.v(TAG + '存在flutter.db');
      try {
        db = await openDatabase(path);
        bool tableIsRight = await this.checkTableIsRight();
        if (!tableIsRight) {
          LogUtil.v(TAG + 'table 中出现了问题');
          createSql.forEach((key, value) {
            db.execute(value);
          });
        }
      } catch (e) {
        LogUtil.v("Error $e");
      }
    } else {
      Directory(dirname(path)).create(recursive: true);
      createSql.forEach((key, value) {
        db.execute(value);
      });
    }
  }

  // 检查数据库中, 表是否完整, 在部份android中, 会出现表丢失的情况
  Future checkTableIsRight() async {
    List<String> tables = await getTables();

    for (int i = 0; i < createSql.length; i++) {
      if (!tables.contains(createSql.keys.toList()[i])) {
        return false;
      }
    }
    return true;
  }
}
